import store from '@/store/'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Vue from 'vue'

/**
 *  WebsocketMixin {
 *      socketUrl  请求地址
 *  }
 */
export const WebsocketMixin = {
    mounted() {
        // 初始化websocket
        this.initWebSocket()
    },
    destroyed: function() {
        // 离开页面生命周期函数
        this.websocketOnclose();
    },
    methods: {
        // 初始化websocket
        initWebSocket: function() {
            if(!this.socketUrl){
                console.log('-----------WebSocket 地址错误-----------')
                return false;
            }
            // let token = Vue.ls.get(ACCESS_TOKEN)
            console.log('-----------WebSocket 连接中-----------')
            // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
            var userId = store.getters.userInfo.id;
            if (!this.socketUrl.startsWith('/')) {
                this.socketUrl = '/' + this.socketUrl
            }
            if (!this.socketUrl.endsWith('/')) {
                this.socketUrl = this.socketUrl + '/'
            }

            var url = window._CONFIG['domianURL']
                .replace('https://', 'wss://')
                .replace('http://', 'ws://')
                + this.socketUrl + userId;
            // + '/' + token
            console.log('-----------WebSocket URL-----------')
            console.log(url)

            // WebSocket构造函数: 新建WebSocket实例后，会创建客户端与服务端的WebSocket连接
            this.websock = new WebSocket(url)
            this.websock.onopen = this.websocketOnopen // 指定连接成功后的回调函数
            this.websock.onerror = this.websocketOnerror // 指定报错时的回调函数
            // -----接收消息-------
            this.websock.onmessage = this.websocketOnmessage // 指定收到服务器数据后的回调函数
            this.websock.onclose = this.websocketOnclose // 指定连接关闭后的回调函数
        },
        websocketOnopen: function() {
            console.log('-----------WebSocket连接成功-----------')
        },
        websocketOnerror: function(e) {
            console.log('-----------WebSocket连接发生错误-----------')
            this.reconnect()
        },
        websocketOnclose: function(e) {
            console.log('-----------WebSocket连接关闭-----------')
            if(this.websock){
                this.websock.close();
                console.log('-----------对话连接已关闭-----------')
            }else{
                this.reconnect()
            }
        },
        // WebSocket实例向后台推送消息的方法
        websocketSend(text) {
            // 数据发送
            try {
                this.websock.send(text)
            } catch (err) {
                console.log('send failed (' + err.code + ')')
            }
        },
        // 重新连接
        reconnect() {
            var that = this
            if (that.lockReconnect) return
            that.lockReconnect = true
            //没连接上会一直重连，设置延迟避免请求过多
            setTimeout(function() {
                console.info('尝试重连...')
                that.initWebSocket()
                that.lockReconnect = false
            }, 10000)
        }
    }

}
